
import './ModifyUserJson.scss'
import { useState } from 'react'
import { Input, Button, Spin, App } from 'antd'
import { useEventEmitter, useMount } from 'ahooks'

import { DrawerBox } from '..'
import { GetIndexedDB, Encrypt, PutIndexedDB } from '../../Utils/IndexedDB'
import { UserAvatar, UserBackboard } from '../../Config/config'

const ModifyUserJson = ({ Off, ModalEvent }) => {
    const { message } = App.useApp()
    const [loading, setLoading] = useState(false)
    const [IndexData, setIndexData] = useState()

    const [Avatar, setAvatar] = useState()
    const [Backboard, setBackboard] = useState()
    const [NickName, setNickName] = useState()

    const [OptionsCall, setOptionsCall] = useState()

    useMount(async () => {
        const IndexData = await GetIndexedDB('theme')
        const { Avatar, Backboard, NickName } = IndexData.userInfo
        setAvatar(Avatar)
        setBackboard(Backboard)
        setNickName(NickName)

        setIndexData(IndexData)
    })

    const SelectAvatar = () => setOptionsCall({ type: 'SelectUserJsonAvatar', title: '选择头像', data: Avatar })
    const SelectBackboard = () => setOptionsCall({ type: 'SelectUserBackboard', title: '选择背景板', data: Backboard })

    const onSave = async () => {
        setLoading(true)
        IndexData.userInfo = { Avatar, Backboard, NickName }
        console.log('保存json文件', await Encrypt(IndexData))
        PutIndexedDB('theme', IndexData)
        message.success('信息更新成功!')
        setTimeout(() => {
            ModalEvent.emit({ type: 'userInfo' })
            Off()
        }, 500)
    }

    const ModalTwoEvent = useEventEmitter()
    ModalTwoEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'BackBoard') setBackboard(data)
        if (type === 'Avatar') setAvatar(data)

    })

    if (IndexData) {
        return (
            <Spin spinning={loading}>
                <div className='ModifyUserJson'>
                    <img className='Backboard' src={UserBackboard[Backboard]} alt="" onClick={SelectBackboard} />
                    <img className='Avatar' src={UserAvatar[Avatar]} alt="" onClick={SelectAvatar} />
                    <div className='NickName'>
                        <Input placeholder='请输入一个昵称' value={NickName} variant="borderless" onChange={e => setNickName(e.target.value)} />
                        <Button type='primary' onClick={onSave}>保存数据</Button>
                    </div>
                    <DrawerBox OptionsCall={OptionsCall} ModalEvent={ModalTwoEvent} />
                </div>
            </Spin>
        )
    }
};

export default ModifyUserJson;